package net.spatula.tally_ho.ui.article.read;

import net.spatula.tally_ho.service.ArticleService;
import net.spatula.tally_ho.service.ServiceResult;
import net.spatula.tally_ho.service.beans.ArticleBean;
import net.spatula.tally_ho.service.beans.UserBean;
import net.spatula.tally_ho.ui.AuthenticatedWebPage;
import net.spatula.tally_ho.ui.signin.Utils;
import wicket.markup.MarkupStream;
import wicket.markup.html.basic.Label;
import wicket.protocol.http.WebRequestCycle;
import wicket.protocol.http.WebResponse;

/**
 * XXX
 * This is a rather inelegant temporary solution to the article voting problem. It is caused by the need of having old code
 * mixed with new code; that is, the old layout and message board system has to mesh with the new article viewing and voting
 * system, at least temporarily.  So we can't redirect back to a proper page, and have to go through this URL construction
 * stuff and redirect nonsense.
 * 
 * This will be corrected in a later version.
 * 
 * @author spatula
 *
 */

public class ArticleVote extends AuthenticatedWebPage {

    private static final long serialVersionUID = 1L;
    private ArticleBean article;
    private String returnTo;

    public static enum VOTE {
        up, down, abuse
    };

    private VOTE which;

    public ArticleVote(ArticleBean article, String returnTo, VOTE which) {
        this.article = article;
        this.returnTo = returnTo;
        this.which = which;

        
    }

    @Override
    protected void onRender(MarkupStream arg0) {
        ArticleService service = ArticleService.getInstance();
        UserBean user = Utils.getUserBean();
        ServiceResult result = null;
        switch (which) {
        case up:
            result = service.voteForArticle(article, user);
            break;
        case down:
            result = service.voteAgainstArticle(article, user);
            break;
        case abuse:
            result = service.flagAsSpamAbuse(article, user);
            break;
        }
        if (result.getStatus() == ServiceResult.STATUS.OK) {
            ((WebResponse) (WebRequestCycle.get().getResponse())).redirect(returnTo);
            add(new Label("error", ""));
            super.onRender(arg0);
        } else {
            add(new Label("error", result.getMessage()));
            super.onRender(arg0);
        }

    }

}
